<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>3. 启用路由和添加静态资源 | 被删的前端游乐场</title>
    <meta name="generator" content="VuePress 1.8.2">
    
    <meta name="description" content="Just playing around">
    
    <link rel="preload" href="/front-end-playground/assets/css/0.styles.6ad2a9ca.css" as="style"><link rel="preload" href="/front-end-playground/assets/js/app.1e2670bf.js" as="script"><link rel="preload" href="/front-end-playground/assets/js/2.38d016d1.js" as="script"><link rel="preload" href="/front-end-playground/assets/js/3.e3f029cb.js" as="script"><link rel="preload" href="/front-end-playground/assets/js/69.df688e95.js" as="script">
    <link rel="stylesheet" href="/front-end-playground/assets/css/0.styles.6ad2a9ca.css">
  </head>
  <body>
    <div id="app" data-server-rendered="true"><div class="theme-container"><header class="navbar"><div class="sidebar-button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" role="img" viewBox="0 0 448 512" class="icon"><path fill="currentColor" d="M436 124H12c-6.627 0-12-5.373-12-12V80c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12z"></path></svg></div> <a href="/front-end-playground/" class="home-link router-link-active"><!----> <span class="site-name">被删的前端游乐场</span></a> <div class="links"><div class="search-box"><input aria-label="Search" autocomplete="off" spellcheck="false" value=""> <!----></div> <nav class="nav-links can-hide"><div class="nav-item"><a href="/front-end-playground/" class="nav-link">概述</a></div><div class="nav-item"><a href="/front-end-playground/front-end-basic/" class="nav-link">前端领域</a></div><div class="nav-item"><a href="/front-end-playground/vue/" class="nav-link">Vue学习</a></div><div class="nav-item"><a href="/front-end-playground/wxapp/" class="nav-link">小程序学习</a></div><div class="nav-item"><a href="/front-end-playground/front-end-others/" class="nav-link router-link-active">百家齐放</a></div><div class="nav-item"><a href="/front-end-playground/front-end-addon/" class="nav-link">前端的进击</a></div><div class="nav-item"><a href="/front-end-playground/front-end-work/" class="nav-link">前端与工作</a></div><div class="nav-item"><a href="/front-end-playground/faq.html" class="nav-link">FAQ</a></div> <a href="https://github.com/godbasin/front-end-playground" target="_blank" rel="noopener noreferrer" class="repo-link">
    Github
    <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></nav></div></header> <div class="sidebar-mask"></div> <aside class="sidebar"><nav class="nav-links"><div class="nav-item"><a href="/front-end-playground/" class="nav-link">概述</a></div><div class="nav-item"><a href="/front-end-playground/front-end-basic/" class="nav-link">前端领域</a></div><div class="nav-item"><a href="/front-end-playground/vue/" class="nav-link">Vue学习</a></div><div class="nav-item"><a href="/front-end-playground/wxapp/" class="nav-link">小程序学习</a></div><div class="nav-item"><a href="/front-end-playground/front-end-others/" class="nav-link router-link-active">百家齐放</a></div><div class="nav-item"><a href="/front-end-playground/front-end-addon/" class="nav-link">前端的进击</a></div><div class="nav-item"><a href="/front-end-playground/front-end-work/" class="nav-link">前端与工作</a></div><div class="nav-item"><a href="/front-end-playground/faq.html" class="nav-link">FAQ</a></div> <a href="https://github.com/godbasin/front-end-playground" target="_blank" rel="noopener noreferrer" class="repo-link">
    Github
    <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></nav>  <ul class="sidebar-links"><li><section class="sidebar-group collapsable depth-0" style="padding-top:;"><!----> <p class="sidebar-heading"><span>Angular框架解读</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable depth-0" style="padding-top:10px;"><div class="kitty-main" data-v-2b653b36><span class="stand" data-v-2b653b36></span> <div class="cat" data-v-2b653b36><div class="body" data-v-2b653b36></div> <div class="head" data-v-2b653b36><div class="ear" data-v-2b653b36></div> <div class="ear" data-v-2b653b36></div></div> <div class="face" data-v-2b653b36><div class="nose" data-v-2b653b36></div> <div class="whisker-container" data-v-2b653b36><div class="whisker" data-v-2b653b36></div> <div class="whisker" data-v-2b653b36></div></div> <div class="whisker-container" data-v-2b653b36><div class="whisker" data-v-2b653b36></div> <div class="whisker" data-v-2b653b36></div></div></div> <div class="tail-container" data-v-2b653b36><div class="tail" data-v-2b653b36><div class="tail" data-v-2b653b36><div class="tail" data-v-2b653b36><div class="tail" data-v-2b653b36><div class="tail" data-v-2b653b36><div class="tail" data-v-2b653b36><div class="tail" data-v-2b653b36></div></div></div></div></div></div></div></div></div></div> <p class="sidebar-heading open"><span>玩转 Angular</span> <span class="arrow down"></span></p> <ul class="sidebar-links sidebar-group-items"><li><a href="/front-end-playground/front-end-others/angular-free/0-about-angular-from-1-to-4.html" class="sidebar-link">谈谈 AngularJS 到 Angular</a></li><li><a href="/front-end-playground/front-end-others/angular-free/0-di-in-angular.html" class="sidebar-link">谈谈 Angular 的依赖注入</a></li><li><a href="/front-end-playground/front-end-others/angular-free/1-init-angular-app-with-webpack.html" class="sidebar-link">1. 用 Webpack 启动 Angular 应用</a></li><li><a href="/front-end-playground/front-end-others/angular-free/2-inprove-app-configuration.html" class="sidebar-link">2. 改善应用配置</a></li><li><a href="/front-end-playground/front-end-others/angular-free/3-init-routes-and-assets.html" aria-current="page" class="active sidebar-link">3. 启用路由和添加静态资源</a><ul class="sidebar-sub-headers"><li class="sidebar-sub-header"><a href="/front-end-playground/front-end-others/angular-free/3-init-routes-and-assets.html#使用路由" class="sidebar-link">使用路由</a></li><li class="sidebar-sub-header"><a href="/front-end-playground/front-end-others/angular-free/3-init-routes-and-assets.html#添加资源加载" class="sidebar-link">添加资源加载</a></li><li class="sidebar-sub-header"><a href="/front-end-playground/front-end-others/angular-free/3-init-routes-and-assets.html#项目结构" class="sidebar-link">项目结构</a></li><li class="sidebar-sub-header"><a href="/front-end-playground/front-end-others/angular-free/3-init-routes-and-assets.html#结束语" class="sidebar-link">结束语</a></li></ul></li><li><a href="/front-end-playground/front-end-others/angular-free/4-create-sidebar.html" class="sidebar-link">4. 制作左侧自动定位菜单</a></li><li><a href="/front-end-playground/front-end-others/angular-free/5-custom-input-component.html" class="sidebar-link">5. 自定义 input 表单控件</a></li><li><a href="/front-end-playground/front-end-others/angular-free/6-two-form-building.html" class="sidebar-link">6. 模型驱动和模板驱动的表单</a></li><li><a href="/front-end-playground/front-end-others/angular-free/7-dynamic-form.html" class="sidebar-link">7. 创建动态表单</a></li><li><a href="/front-end-playground/front-end-others/angular-free/8-radio-and-checkbox.html" class="sidebar-link">8. 表单的 radio 和 checkbox</a></li><li><a href="/front-end-playground/front-end-others/angular-free/9-upload-iamge.html" class="sidebar-link">9. 图片上传控件</a></li><li><a href="/front-end-playground/front-end-others/angular-free/10-add-conditions.html" class="sidebar-link">10. 向表单添加条件控制</a></li><li><a href="/front-end-playground/front-end-others/angular-free/11-option-dialog.html" class="sidebar-link">11. 使用动态表单制作选项配置对话框</a></li><li><a href="/front-end-playground/front-end-others/angular-free/12-config-and-create-form.html" class="sidebar-link">12. 配置以及生成表单</a></li><li><a href="/front-end-playground/front-end-others/angular-free/13-dynamic-list.html" class="sidebar-link">13. 动态列表配置</a></li></ul></section></li><li><section class="sidebar-group collapsable depth-0" style="padding-top:;"><!----> <p class="sidebar-heading"><span>试试 Cycle.js</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable depth-0" style="padding-top:;"><!----> <p class="sidebar-heading"><span>D3.js 和 Tree</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable depth-0" style="padding-top:;"><!----> <p class="sidebar-heading"><span>试试 Three.js</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable depth-0" style="padding-top:;"><!----> <p class="sidebar-heading"><span>BOX2D.js 文档与教程</span> <span class="arrow right"></span></p> <!----></section></li></ul> </aside> <main class="page"> <div class="theme-default-content content__default"><p>该系列用于探索一些 Angular 中灵活或者新的用法。本文记录启用路由 Router，以及添加静态资源的过程。</p> <h2 id="使用路由"><a href="#使用路由" class="header-anchor">#</a> 使用路由</h2> <h3 id="有关路由"><a href="#有关路由" class="header-anchor">#</a> 有关路由</h3> <p>现在流行的前端框架，像 React/Vue/Angular 等，都不可避免地自带路由模块。</p> <p>要说为什么呢，本骚年是这么认为的（个人意见仅供参考）：</p> <ol><li>单页应用已经十分流行了，尤其在 PC 端，而使用前端路由，配合模块化，便使得开发单页应用得心应手。</li> <li>路由的设计很简单，事件的监听配合框架自行封装的一些<code>[router-link]</code>等组件，便在开发效率锦上添花。</li></ol> <p>(本骚年也不知道为啥突然懂得这么多的成语，开心逃</p> <ul><li>Angular 的 Router</li></ul> <p>Angular 的 Router 借鉴了浏览器的导航模型。它把浏览器中的 URL 看做一个操作指南， 据此导航到一个由客户端生成的视图，并可以把参数传给支撑视图的相应组件，帮它决定具体该展现哪些内容。</p> <p>路由器还在浏览器的历史日志中记录下这些活动，这样浏览器的前进和后退按钮也能照常工作。</p> <h3 id="在视图中跳转"><a href="#在视图中跳转" class="header-anchor">#</a> 在视图中跳转</h3> <p>这里只介绍常用的两种，它们都需要在 A 标签上使用：</p> <ul><li>[routerLink]属性</li></ul> <p>不用说，一看就知道<code>[routerLink]</code>属性是用来定位到具体的路由的，当然我们同样可以使用 angular 中常用的绑定来传入需要的变量。</p> <ul><li>[routerLinkActive]属性</li></ul> <p>该属性可配置在带<code>[routerLink]</code>属性的 A 标签上，则当<code>[routerLink]</code>对应的路由被触发了，则<code>[routerLinkActive]</code>绑定的 Class 样式将被激活。</p> <h3 id="注册路由模块"><a href="#注册路由模块" class="header-anchor">#</a> 注册路由模块</h3> <p>在 Angular 的 release 版本开始，加入了 NgModule 这样一个模块设计，首先我们需注册这样一个路由模块：</p> <div class="language-js extra-class"><pre class="language-js"><code><span class="token keyword">import</span> <span class="token punctuation">{</span> NgModule <span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">'@angular/core'</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token punctuation">{</span> RouterModule<span class="token punctuation">,</span> Routes <span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">'@angular/router'</span><span class="token punctuation">;</span>
<span class="token operator">...</span> <span class="token comment">// 引入其他Component</span>

<span class="token keyword">const</span> appRoutes<span class="token operator">:</span> Routes <span class="token operator">=</span> <span class="token punctuation">[</span>
  <span class="token punctuation">{</span> path<span class="token operator">:</span> <span class="token string">'one-path'</span><span class="token punctuation">,</span> component<span class="token operator">:</span> OneComponent <span class="token punctuation">}</span><span class="token punctuation">,</span>
  <span class="token punctuation">{</span> path<span class="token operator">:</span> <span class="token string">'other-path'</span><span class="token punctuation">,</span> component<span class="token operator">:</span> OtherComponent <span class="token punctuation">}</span><span class="token punctuation">,</span>
  <span class="token punctuation">{</span> path<span class="token operator">:</span> <span class="token string">'**'</span><span class="token punctuation">,</span> redirectTo<span class="token operator">:</span> <span class="token string">'one-path'</span> <span class="token punctuation">}</span>
<span class="token punctuation">]</span><span class="token punctuation">;</span>

@<span class="token function">NgModule</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  imports<span class="token operator">:</span> <span class="token punctuation">[</span>
    RouterModule<span class="token punctuation">.</span><span class="token function">forRoot</span><span class="token punctuation">(</span>appRoutes<span class="token punctuation">)</span>
  <span class="token punctuation">]</span><span class="token punctuation">,</span>
  exports<span class="token operator">:</span> <span class="token punctuation">[</span>
    RouterModule
  <span class="token punctuation">]</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">AppRoutingModule</span> <span class="token punctuation">{</span><span class="token punctuation">}</span>
</code></pre></div><ul><li>根路由注册使用<code>RouterModule.forRoot()</code></li> <li>子路由注册使用<code>RouterModule.forChild()</code></li></ul> <p>对于根路由和子路由，一个应用有一个根路由，但可以有多个子路由，像我们的 DOM 树结构一样，层层向下伸展。</p> <p>这样的设计思想现在也很流行了，像还有 Angular 中的依赖注入 DI，或者是 React 的虚拟 DOM 设计等。</p> <h3 id="使用-router"><a href="#使用-router" class="header-anchor">#</a> 使用 Router</h3> <ul><li>在 js 中跳转</li></ul> <p>一般来说，我们使用<code>router.navigate()</code>来进行跳转，像我们的登陆页面：</p> <div class="language-js extra-class"><pre class="language-js"><code><span class="token keyword">import</span> <span class="token punctuation">{</span> Component <span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">'@angular/core'</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token punctuation">{</span> Router <span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">'@angular/router'</span><span class="token punctuation">;</span>

@<span class="token function">Component</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">'app-login'</span><span class="token punctuation">,</span>
  templateUrl<span class="token operator">:</span> <span class="token string">'./login.component.html'</span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">LoginComponent</span> <span class="token keyword">implements</span> <span class="token class-name">OnInit</span><span class="token punctuation">,</span> OnDestroy <span class="token punctuation">{</span>
  <span class="token comment">// 注入router</span>
  <span class="token function">constructor</span><span class="token punctuation">(</span><span class="token parameter"><span class="token keyword">private</span> router<span class="token operator">:</span> Router</span><span class="token punctuation">)</span> <span class="token punctuation">{</span><span class="token punctuation">}</span>

  <span class="token comment">// 登录事件</span>
  <span class="token function">onSubmit</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>router<span class="token punctuation">.</span><span class="token function">navigate</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token string">'/home'</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div><p>当然，<code>router.navigate()</code>还可以传入其他的 params，使用方法大家可以查阅文档。</p> <ul><li>监听路由</li></ul> <p>在 Angular2 的 release 版本之后，路由进行了调整，我们需要通过<code>subscribe()</code>这样的方式对事件进行订阅：</p> <div class="language-js extra-class"><pre class="language-js"><code><span class="token comment">// 监听导航事件变更</span>
<span class="token comment">// NavigationEnd表示导航事件变更完毕</span>
<span class="token comment">// 通过对事件进行filter过滤，我们可以订阅想要的路由事件消息</span>
router<span class="token punctuation">.</span>events
  <span class="token punctuation">.</span><span class="token function">filter</span><span class="token punctuation">(</span><span class="token parameter">event</span> <span class="token operator">=&gt;</span> event <span class="token keyword">instanceof</span> <span class="token class-name">NavigationEnd</span><span class="token punctuation">)</span>
  <span class="token punctuation">.</span><span class="token function">subscribe</span><span class="token punctuation">(</span><span class="token parameter">event</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div><p>若要写面包屑功能，可参考该文章<a href="http://brianflove.com/2016/10/23/angular2-breadcrumb-using-router/" target="_blank" rel="noopener noreferrer">Angular2 Breadcrumb using Router<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>。</p> <h3 id="获取路由信息"><a href="#获取路由信息" class="header-anchor">#</a> 获取路由信息</h3> <ul><li>ActivatedRoute：一站式获取路由信息</li></ul> <p>路由的路径和参数可以通过注入<code>ActivatedRoute</code>的路由服务来获取，包括：</p> <ul><li>url: 该路由路径的 Observable 对象。它的值是一个由路径中各个部件组成的字符串数组</li> <li>data: 该路由提供的 data 对象的一个 Observable 对象。还包含从 resolve 中解析出来的值</li> <li>params: 包含该路由的必选参数和可选参数的 Observable 对象</li> <li>queryParams: 一个包含对所有路由都有效的查询参数的 Observable 对象</li> <li>fragment: 一个包含对所有路由都有效的片段值的 Observable 对象</li> <li>outlet: RouterOutlet 的名字，用于指示渲染该路由的位置</li> <li>routeConfig: 与该路由的原始路径对应的配置信息</li> <li>firstChild: 包含子路由列表中的第一个 ActivatedRoute 对象</li> <li>children: 包含当前路由下激活的全部子路由</li></ul> <p>通常我们可能这样使用：</p> <div class="language-js extra-class"><pre class="language-js"><code><span class="token keyword">import</span> <span class="token punctuation">{</span> ActivatedRoute <span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">'@angular/router'</span><span class="token punctuation">;</span>
<span class="token operator">...</span> <span class="token comment">// 其余代码</span>

	<span class="token comment">// 注入route</span>
  	<span class="token function">constructor</span><span class="token punctuation">(</span><span class="token parameter"><span class="token keyword">private</span> route<span class="token operator">:</span> ActivatedRoute</span><span class="token punctuation">)</span> <span class="token punctuation">{</span><span class="token punctuation">}</span>
    <span class="token function">ngOnInit</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      <span class="token keyword">this</span><span class="token punctuation">.</span>route<span class="token punctuation">.</span>params
        <span class="token punctuation">.</span><span class="token function">subscribe</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token parameter">params</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
		  <span class="token comment">// 获取名为id的param参数</span>
          <span class="token keyword">this</span><span class="token punctuation">.</span>id <span class="token operator">=</span> <span class="token function">parseInt</span><span class="token punctuation">(</span>params<span class="token punctuation">[</span><span class="token string">'id'</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
         <span class="token operator">...</span> <span class="token comment">// 其余代码</span>
        <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

<span class="token operator">...</span> <span class="token comment">// 其余代码</span>
</code></pre></div><h3 id="lazyload"><a href="#lazyload" class="header-anchor">#</a> lazyload</h3> <p>对于一些路由子模块，我们可以通过懒加载来定义，这样就可以只在进入到该路由时进行加载，也算是首屏加载优化的一种方法吧。</p> <p>一般我们在路由中这样定义：</p> <div class="language-js extra-class"><pre class="language-js"><code><span class="token keyword">export</span> <span class="token keyword">const</span> AppRoutes<span class="token operator">:</span> Routes <span class="token operator">=</span> <span class="token punctuation">[</span>
  <span class="token punctuation">{</span>
    path<span class="token operator">:</span> <span class="token string">&quot;&quot;</span><span class="token punctuation">,</span>
    component<span class="token operator">:</span> AppComponent<span class="token punctuation">,</span>
    children<span class="token operator">:</span> <span class="token punctuation">[</span><span class="token punctuation">{</span> path<span class="token operator">:</span> <span class="token string">&quot;home&quot;</span><span class="token punctuation">,</span> loadChildren<span class="token operator">:</span> <span class="token string">&quot;lazy/lazy.module#LazyModule&quot;</span> <span class="token punctuation">}</span><span class="token punctuation">]</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">]</span><span class="token punctuation">;</span>
</code></pre></div><p>就可以对该部分进行懒加载了，当然懒加载还需要其他依赖或者一些另外的配置支持，其实安装一个<code>angular-router-loader</code>就好了：</p> <div class="language-js extra-class"><pre class="language-js"><code>npm install <span class="token operator">--</span>save<span class="token operator">-</span>dev angular<span class="token operator">-</span>router<span class="token operator">-</span>loader
</code></pre></div><p>然后在 webpack 的 rules 中调整：</p> <div class="language-js extra-class"><pre class="language-js"><code><span class="token punctuation">{</span>
  test<span class="token operator">:</span> <span class="token regex"><span class="token regex-delimiter">/</span><span class="token regex-source language-regex">\.ts$</span><span class="token regex-delimiter">/</span></span><span class="token punctuation">,</span>
  use<span class="token operator">:</span> <span class="token punctuation">[</span><span class="token string">&quot;babel-loader&quot;</span><span class="token punctuation">,</span> <span class="token string">&quot;ts-loader&quot;</span><span class="token punctuation">,</span> <span class="token string">&quot;angular2-template-loader&quot;</span><span class="token punctuation">,</span> <span class="token string">&quot;angular-router-loader&quot;</span><span class="token punctuation">]</span><span class="token punctuation">,</span>
  exclude<span class="token operator">:</span> <span class="token regex"><span class="token regex-delimiter">/</span><span class="token regex-source language-regex">node_modules</span><span class="token regex-delimiter">/</span></span>
<span class="token punctuation">}</span>
</code></pre></div><p>打包的时候我们会发现，除了主文件<code>bundle.js</code>，每一个使用 lazyload 的文件都会单独打包成一个<code>n.bundle.js</code>文件（n 为数字），用于异步请求和加载。</p> <h2 id="添加资源加载"><a href="#添加资源加载" class="header-anchor">#</a> 添加资源加载</h2> <p>一般来说，项目多业务杂，我们总不能一个个插件都自己实现，故很多时候我们需要使用到像 jQuery 或者 Bootstrap 这样很常用的库。</p> <h3 id="全局注入-js"><a href="#全局注入-js" class="header-anchor">#</a> 全局注入 js</h3> <p>本骚年使用了一种最蠢的方式来实现[捂脸]：</p> <div class="language-js extra-class"><pre class="language-js"><code><span class="token comment">// jquery</span>
window<span class="token punctuation">[</span><span class="token string">&quot;$&quot;</span><span class="token punctuation">]</span> <span class="token operator">=</span> window<span class="token punctuation">[</span><span class="token string">&quot;jQuery&quot;</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span><span class="token string">&quot;./assets/js/jquery.min.js&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// boootstrap</span>
<span class="token function">require</span><span class="token punctuation">(</span><span class="token string">&quot;../node_modules/bootstrap/dist/js/bootstrap.min.js&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div><p>当然，身为懒癌晚期的我还使用了 typescript 的杀手锏[捂脸+1]：</p> <div class="language-js extra-class"><pre class="language-js"><code><span class="token comment">// declation.d.ts</span>
declare <span class="token keyword">var</span> $<span class="token operator">:</span> any<span class="token punctuation">;</span>
declare <span class="token keyword">var</span> JQuery<span class="token operator">:</span> any<span class="token punctuation">;</span>
</code></pre></div><p>其实在 typescript 中使用 jQuery 也有很多现成的<code>@types</code>库，大家可以一键安装使用就好了：</p> <div class="language-js extra-class"><pre class="language-js"><code>npm install @types<span class="token operator">/</span>jquery
</code></pre></div><p>完整的项目还是需要完善的，像本骚年这种业余玩玩的小项目就另当其说了，而且说不定后面我也会完善的吧[摊手]。</p> <h3 id="全局注入-css"><a href="#全局注入-css" class="header-anchor">#</a> 全局注入 css</h3> <p>像<code>import 'someStyle.css'</code>这样的方法竟然没有成功，可能是本骚年的 webpack 配置或者是 loader 哪里出了问题吧。</p> <p>然后就找了一个懒方法，利用的是<code>ViewEncapsulation</code>，在组件中将<code>styleUrls</code>定义为全局生效，如下：</p> <div class="language-js extra-class"><pre class="language-js"><code><span class="token keyword">import</span> <span class="token punctuation">{</span> Component<span class="token punctuation">,</span> ViewEncapsulation <span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">'@angular/core'</span><span class="token punctuation">;</span>

@<span class="token function">Component</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">'app-root'</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token string">' &lt;router-outlet&gt;&lt;/router-outlet&gt;'</span><span class="token punctuation">,</span>
  styleUrls<span class="token operator">:</span> <span class="token punctuation">[</span>
      <span class="token string">'../../../node_modules/bootstrap/dist/css/bootstrap.min.css'</span><span class="token punctuation">,</span>
    <span class="token string">'../../assets/css/common.css'</span><span class="token punctuation">,</span>
    <span class="token string">'../../assets/css/custom.css'</span>
  <span class="token punctuation">]</span><span class="token punctuation">,</span>
  encapsulation<span class="token operator">:</span> ViewEncapsulation<span class="token punctuation">.</span>None
<span class="token punctuation">}</span><span class="token punctuation">)</span>
</code></pre></div><h2 id="项目结构"><a href="#项目结构" class="header-anchor">#</a> 项目结构</h2> <h3 id="目录"><a href="#目录" class="header-anchor">#</a> 目录</h3> <p>如图：
<img src="https://github-imglib-1255459943.cos.ap-chengdu.myqcloud.com/1495034687%281%29.png" alt="image"></p> <h3 id="其他配置文件调整"><a href="#其他配置文件调整" class="header-anchor">#</a> 其他配置文件调整</h3> <ul><li>package.json</li></ul> <p>移除<code>@angular/compiler-cli</code>，该依赖为 AOT 使用，而目前本骚年还没做这方面的配置，光一个<code>compiler-cli</code>也是不够的，后面需要的时候再加吧</p> <ul><li>tsconfig.json</li></ul> <p>这个不得不说了，项目一直起不来提示如下：</p> <div class="language-cmd extra-class"><pre class="language-text"><code>compiler.es5.js:15291
Uncaught Error: Can't resolve all parameters for LoginComponent: (?).
    at syntaxError (webpack:///./~/@angular/compiler/@angular/compiler.es5.js?:1724:34)
    at CompileMetadataResolver._getDependenciesMetadata (webpack:///./~/@angular/compiler/@angular/compiler.es5.js?:15061:35)
    at CompileMetadataResolver._getTypeMetadata (webpack:///./~/@angular/compiler/@angular/compiler.es5.js?:14929:26)
    at CompileMetadataResolver.getNonNormalizedDirectiveMetadata (webpack:///./~/@angular/compiler/@angular/compiler.es5.js?:14538:24)
    at CompileMetadataResolver._getEntryComponentMetadata (webpack:///./~/@angular/compiler/@angular/compiler.es5.js?:15182:45)
    at eval (webpack:///./~/@angular/compiler/@angular/compiler.es5.js?:15168:48)
    at Array.forEach (native)
    at CompileMetadataResolver._getEntryComponentsFromProvider (webpack:///./~/@angular/compiler/@angular/compiler.es5.js?:15167:30)
    at eval (webpack:///./~/@angular/compiler/@angular/compiler.es5.js?:15131:83)
    at Array.forEach (native)
</code></pre></div><p>哭死我了，后面是改了一个<code>tsconfig.json</code>配置解决的：</p> <div class="language-json extra-class"><pre class="language-json"><code><span class="token property">&quot;emitDecoratorMetadata&quot;</span><span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span> &lt;= 就是这家伙
</code></pre></div><p>大家也可以尽情嘲笑我，本骚年有时候就是转不过来。</p> <ul><li>webpack.config.js</li></ul> <div class="language-js extra-class"><pre class="language-js"><code><span class="token comment">// 加了个插件，关闭之前的黄色warning</span>
<span class="token keyword">new</span> <span class="token class-name">webpack<span class="token punctuation">.</span>ContextReplacementPlugin</span><span class="token punctuation">(</span>
  <span class="token regex"><span class="token regex-delimiter">/</span><span class="token regex-source language-regex">angular(\\|\/)core(\\|\/)@angular</span><span class="token regex-delimiter">/</span></span><span class="token punctuation">,</span>
  path<span class="token punctuation">.</span><span class="token function">resolve</span><span class="token punctuation">(</span>__dirname<span class="token punctuation">,</span> <span class="token string">&quot;src&quot;</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
  <span class="token punctuation">{</span><span class="token punctuation">}</span>
<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div><p>登录页面也还是我们熟悉的：</p> <p><img src="https://github-imglib-1255459943.cos.ap-chengdu.myqcloud.com/1495970476%281%29.png" alt="image"></p> <h2 id="结束语"><a href="#结束语" class="header-anchor">#</a> 结束语</h2> <p>这节主要讲了路由相关的介绍和使用，以及添加静态资源，和调整一些配置使得项目得以启动的过程。项目里代码讲得不多，大家可以自行查看。<br> <a href="https://github.com/godbasin/godbasin.github.io/tree/blog-codes/angular2-free/3-init-routes-and-assets" target="_blank" rel="noopener noreferrer">此处查看项目代码<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a><br> <a href="http://angular2-free.godbasin.com/3-init-routes-and-assets/index.html" target="_blank" rel="noopener noreferrer">此处查看页面效果<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></p></div> <!----> <footer class="page-edit"><div class="edit-link"><a href="https://github.com/godbasin/front-end-playground/edit/sourcecode/docs/front-end-others/angular-free/3-init-routes-and-assets.md" target="_blank" rel="noopener noreferrer">帮阿猪改善此页面！</a> <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></div> <!----> <blockquote>部分文章中使用了一些网站的截图，如果涉及侵权，请告诉我删一下谢谢~</blockquote> <div style="margin-top:30px;"><div class="el-row" style="margin-left:-10px;margin-right:-10px;"><div class="el-col el-col-24 el-col-sm-0 el-col-md-2 el-col-lg-4" style="padding-left:10px;padding-right:10px;display:block;"><div style="width:1px;height:1px;"></div></div> <div class="el-col el-col-24 el-col-sm-24 el-col-md-18 el-col-lg-16" style="padding-left:10px;padding-right:10px;"><div class="el-card box-card is-always-shadow"><div class="el-card__header"><div class="clearfix"><span>温馨提示喵</span></div></div><div class="el-card__body"> <div class="el-row" style="margin-left:-10px;margin-right:-10px;"><div class="el-col el-col-24 el-col-xs-24 el-col-sm-12" style="padding-left:10px;padding-right:10px;"><div class="el-image"><div class="image-slot"><img src="https://github-imglib-1255459943.cos.ap-chengdu.myqcloud.com/assets/img/loading.gif" style="width:100%;"></div><!----></div></div> <div class="el-col el-col-24 el-col-xs-24 el-col-sm-12" style="padding-left:10px;padding-right:10px;"><div class="copyright-text"><div>本文版权归作者所有，欢迎转载，但未经作者同意必须保留此段声明，且在文章页面明显位置给出原文连接，否则保留追究法律责任的权利。</div> <div>出处：被删的前端游乐场</div> <div>作者：<a href="https://github.com/godbasin" target="_blank">被删</a></div></div></div></div></div></div></div></div></div></footer> <div class="page-nav"><p class="inner"><span class="prev">
        ←
        <a href="/front-end-playground/front-end-others/angular-free/2-inprove-app-configuration.html" class="prev">
          2. 改善应用配置
        </a></span> <span class="next"><a href="/front-end-playground/front-end-others/angular-free/4-create-sidebar.html">
          4. 制作左侧自动定位菜单
        </a>
        →
      </span></p></div>  <div class="gitalk-container theme-default-content"><div id="gitalk-container" class="content"></div></div></main> <div id="kitty-container"><span><div role="tooltip" id="el-popover-8807" aria-hidden="true" class="el-popover el-popper" style="width:undefinedpx;display:none;"><!----><img src="https://github-imglib-1255459943.cos.ap-chengdu.myqcloud.com/2code2.jpg" class="image"> <div class="text">牡羊猪的猫粮罐</div> </div><span class="el-popover__reference-wrapper"><div id="kitty" style="background:url(https://github-imglib-1255459943.cos.ap-chengdu.myqcloud.com/assets/img/kitty1.svg);"></div></span></span> <div class="el-dialog__wrapper" style="display:none;"><div role="dialog" aria-modal="true" aria-label="牡羊猪是这样渐渐胖成猪的喵（点击图片可以切换噢）" class="el-dialog" style="margin-top:15vh;"><div class="el-dialog__header"><span class="el-dialog__title">牡羊猪是这样渐渐胖成猪的喵（点击图片可以切换噢）</span><button type="button" aria-label="Close" class="el-dialog__headerbtn"><i class="el-dialog__close el-icon el-icon-close"></i></button></div><!----><!----></div></div></div></div><div class="global-ui"></div></div>
    <script src="/front-end-playground/assets/js/app.1e2670bf.js" defer></script><script src="/front-end-playground/assets/js/2.38d016d1.js" defer></script><script src="/front-end-playground/assets/js/3.e3f029cb.js" defer></script><script src="/front-end-playground/assets/js/69.df688e95.js" defer></script>
  </body>
</html>
